package 文件IO.查看目录下的所有文件名;

import java.io.*;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        //1.必要内容信息
        Scanner sc = new Scanner(System.in);
        System.out.println("输入搜索路径 :");
        String path = sc.next();

        //2.判断合法
        File rootFile = new File(path);
        if(!rootFile.isDirectory()){
            System.out.println("您输入的不合法" + path);
            return;
        }
        //3.递归查找
        search(rootFile);
    }
    public static void search(File rootFile){
        File[] files = rootFile.listFiles();
        if(files == null){
            return;
        }
        for(File f : files){
            if(f.isFile()){
                //文件内容搜索
                matchWord(f);
            }else if(f.isDirectory()){
                //文件递归
                search(f);
            }
        }
    }

    private static void matchWord(File f) {
        File outputFile = new File("output.txt"); // 输出文件

        // 负责文件读取和判定
        try (FileReader reader = new FileReader(f);
             FileWriter fileWriter = new FileWriter(outputFile, true); // true表示追加模式
             PrintWriter printWriter = new PrintWriter(fileWriter)) {

            // 把结果放到 StringBuilder
            StringBuilder stringBuilder = new StringBuilder();
            int c;
            while ((c = reader.read()) != -1) {
                stringBuilder.append((char) c);
            }

            // 将信息写入到 output.txt
            printWriter.println("找到了:" + f.getAbsoluteFile());
            System.out.println("已写入到文件: " + outputFile.getAbsoluteFile());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

